Skip to content

Instantly share code, notes, and snippets.

@ahmu83
Created May 20, 2024 13:58
Show Gist options
  • Save ahmu83/5f004f93878f535083ee97695830ddec to your computer and use it in GitHub Desktop.
Save ahmu83/5f004f93878f535083ee97695830ddec to your computer and use it in GitHub Desktop.
This is a Bash script to import a MySQL database using either standard TCP/IP connections or Unix sockets
#!/bin/bash
# USAGE:
#
# sh import-mysql-db.sh
# bash import-mysql-db.sh
#
# OR
#
# chmod +x import-mysql-db.sh
# ./import-mysql-db.sh
# Set database parameters
DB_USER="your_username"
DB_HOST="localhost"
DB_NAME="your_database_name"
DB_FILE="your_db_file_path"
DB_PASSWORD="your_password" # Optional: hardcode your password here
DB_SOCKET="" # Set default socket or empty if not using
# DB_SOCKET="/tmp/mysql_3306.sock" # Set default socket or empty if not using
# Check if the SQL file exists
if [ ! -f "$DB_FILE" ]; then
echo "Error: SQL file does not exist."
exit 1
fi
# Check if a socket file is used
if [ -n "$DB_SOCKET" ] && [ -S "$DB_SOCKET" ]; then
SOCKET_OPTION="-S $DB_SOCKET"
else
SOCKET_OPTION=""
fi
# Check if DB_PASSWORD is set
if [ -z "$DB_PASSWORD" ]; then
# Prompt for the MySQL password if not set
echo -n "Enter MySQL password for user $DB_USER: "
read -s DB_PASSWORD
echo
fi
# Run the MySQL import command
if [ -n "$SOCKET_OPTION" ]; then
mysql $SOCKET_OPTION -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" < "$DB_FILE"
else
mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" < "$DB_FILE"
fi
if [ $? -eq 0 ]; then
echo "Database import successful."
else
echo "Database import failed."
fi
@ahmu83
Copy link
Author

ahmu83 commented May 20, 2024

This is a Bash script to import a MySQL database using either standard TCP/IP connections or Unix sockets. Designed to support both manual password entry and automated deployments with hardcoded passwords.

It checks for the presence of the specified SQL file before proceeding with the import to prevent errors, and it provides clear success or failure messages based on the import results.

This utility is ideal for developers and system administrators who frequently manage database migrations and updates.

Usage Instructions

If you are using a socket you can provide that in the script (DB_SOCKET) or leave it empty.

sh import-mysql-db.sh

OR

chmod +x import-mysql-db.sh ./import-mysql-db.sh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment